package com.prs.crm.dao.hr.impl;

import java.util.Collection;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.prs.crm.dao.hr.DeptDao;
import com.prs.crm.dao.impl.BaseDaoImpl;
import com.prs.crm.domain.hr.Dept;

public class DeptDaoImpl extends BaseDaoImpl<Dept> implements DeptDao{
	
	@SuppressWarnings("unchecked")
	public Collection<Dept> getAllDepts()
	{
		return (Collection<Dept>)this.getHibernateTemplate().execute(
				new HibernateCallback()
				{
					public Object doInHibernate(Session session) throws HibernateException {
			        	Criteria criteria = session.createCriteria(Dept.class);
			        	criteria.addOrder(Order.asc("id"));
			        	return criteria.list();
			        }   
				}
		);
		
	}
	
	@SuppressWarnings("unchecked")
	public Collection<Dept> getRootDepts()
	{
		return (Collection<Dept>)this.getHibernateTemplate().execute(
				new HibernateCallback()
				{
					public Object doInHibernate(Session session) throws HibernateException {
			        	Criteria criteria = session.createCriteria(Dept.class);
			        	criteria.add(Restrictions.isNull("parent"));
			        	criteria.addOrder(Order.asc("id"));
			        	return criteria.list();
			        }   
				}
		);
	}

	@SuppressWarnings("unchecked")
	public List<Dept> getAllDept() {
		return (List<Dept>)this.getHibernateTemplate().execute(
				new HibernateCallback()
				{
					public Object doInHibernate(Session session) throws HibernateException {
				Criteria criteria = session.createCriteria(Dept.class);
				return criteria.list();
			  }
				}
		);
	}

	@SuppressWarnings("unchecked")
	public Dept getDeptByName(final String name) {
		// TODO Auto-generated method stub
		return (Dept)this.getHibernateTemplate().execute(new HibernateCallback(){
					public Object doInHibernate(Session session) throws HibernateException {
			        	Criteria criteria = session.createCriteria(Dept.class);
			        	criteria.add(Restrictions.eq("name", name));
			        	List<Dept> list = criteria.list();
			        	if(list.size() == 0){
			        		return null;
			        	}else{
			        		return list.get(0);
			        	}
			        }   
				}
		);
	}
}
